package wechat

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

type TemplateGradeNoticeDataValue struct {
	Value string `json:"value"`
}

type TemplateGradeNoticeData struct {
	First    TemplateGradeNoticeDataValue `json:"first"`
	Keyword1 TemplateGradeNoticeDataValue `json:"keyword1"` // 学生姓名
	Keyword2 TemplateGradeNoticeDataValue `json:"keyword2"` // 考试名称
	Keyword3 TemplateGradeNoticeDataValue `json:"keyword3"` // 考试成绩
	Remark   TemplateGradeNoticeDataValue `json:"remark"`
}

type TemplateGradeNotice struct {
	Touser     string                  `json:"touser"`
	TemplateId string                  `json:"template_id"`
	Url        string                  `json:"url"`
	Data       TemplateGradeNoticeData `json:"data"`
}

type TemplateGradeNoticeRes struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	Msgid   int64  `json:"msgid"`
}

// 发送成绩通知
func SendGradeNotice(openid string, first string, remark string, url string, k1 string, k2 string, k3 string) {
	t := TemplateGradeNotice{
		Touser:     openid,
		TemplateId: beego.AppConfig.String("gradenoticeid"),
		Url:        url,
		Data: TemplateGradeNoticeData{
			First:    TemplateGradeNoticeDataValue{Value: first},
			Keyword1: TemplateGradeNoticeDataValue{Value: k1},
			Keyword2: TemplateGradeNoticeDataValue{Value: k2},
			Keyword3: TemplateGradeNoticeDataValue{Value: k3},
			Remark:   TemplateGradeNoticeDataValue{Value: remark},
		},
	}
	content, err := json.Marshal(t)
	if err != nil {
		logs.Error("can not marshal grade notice struct:", err)
		return
	}
	ret := SendTemplateMsg("anban", string(content))
	res := TemplateGradeNoticeRes{}
	err = json.Unmarshal([]byte(ret), &res)
	if err != nil {
		logs.Error("can not unmarshal send grade notice response:", err)
		return
	}
	if res.Errcode != 0 {
		logs.Error("send grade notice fail:", res.Errmsg)
		return
	}
}
